package org.manon.json.asm;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public abstract class MethodVisitorTemplate<T extends ASMContext> {
	
	private final int _access;
	private final String _name;
	private final String _desc;
	private final String _signature;
	private final String[] _exceptions;
	private final int _returnInsn; 
	
	private T _context;
	
	public MethodVisitorTemplate(int access, String name, String desc,String signature,String[] exceptions) {
		this(access,name,desc,signature,exceptions,Opcodes.RETURN);
	}
	
	public MethodVisitorTemplate(int access, String name, String desc,String signature,String[] exceptions, int returnInsn) {
		_access = access;
		_name = name;
		_desc = desc;
		_signature = signature;
		_exceptions = exceptions;
		_returnInsn = returnInsn;
	}

	void setContext(T context) {
		_context = context;
	}
	
	void create() throws Exception {
		final MethodVisitor methodVisitor = _context.getClassWriter().visitMethod(_access, _name, _desc, _signature, _exceptions);
		methodVisitor.visitCode();
		doCreate(_context,methodVisitor);
		methodVisitor.visitInsn(_returnInsn);
		methodVisitor.visitMaxs(1,1);
		methodVisitor.visitEnd();
	}
	
	protected abstract void doCreate(T context,MethodVisitor methodVisitor) throws Exception;
	
}